import {
  insuranceList,
  insuranceDetail,
  insuranceAdd,
  insuranceEdit,
  generatedBills,
  deleteInsurance,
  selectAll,
} from '@/services/insurance';
import prompt from '@/components/Prompt';

export default {
  namespace: 'insurance',

  state: {
    insuranceList: {},
    detail: {},
  },

  effects: {
    *insuranceList({ payload, callback }, { call, put }) {
      const response = yield call(insuranceList, payload);
      if (response.code === 0) {
        const { list, pageSize, total, pageNum } = response.data;
        yield put({
          type: 'list',
          payload: {
            insuranceList: {
              pagination: {
                current: pageNum,
                pageSize,
                total,
              },
              list,
            },
          },
        });
        callback && callback(list);
      }
    },
    *selectAll({ payload, callback }, { call }) {
      const response = yield call(selectAll, payload);
      if (response.code === 0) {
        prompt({ content: `账单生成${response.message}!` });
        if (callback) callback(response.data);
      } else {
        if (callback) callback();
      }
    },
    *insuranceDetail({ payload, callback }, { call, put }) {
      const response = yield call(insuranceDetail, payload);
      if (response.code === 0) {
        yield put({
          type: 'detail',
          payload: {
            detail: { [payload.id]: response.data },
          },
        });
        callback && callback(response.data);
      }
    },
    *insuranceOperate({ payload, callback }, { call }) {
      const response = yield call(payload.id ? insuranceEdit : insuranceAdd, payload);
      const message = payload.id ? `编辑${response.message}` : `新增${response.message}`;
      if (response.code === 0) {
        prompt({ content: message });
        if (callback) callback(response.data);
      }
    },
    /**
     * 生成账单
     */
    *generatedBills({ payload, callback }, { call }) {
      const response = yield call(generatedBills, payload);
      const { code, message, data } = response;
      if (code === 0) {
        prompt({ content: `账单生成${message}!` });
        callback && callback(data);
      }
    },
    *deleteInsurance({ payload, callback }, { call }) {
      const response = yield call(deleteInsurance, payload);
      const { code, message } = response;
      if (code === 0) {
        prompt({ content: `删除${message}` });
        callback && callback();
      }
    },
  },

  reducers: {
    list(state, { payload }) {
      return {
        ...state,
        insuranceList: payload.insuranceList,
      };
    },
    detail(state, { payload }) {
      return {
        ...state,
        detail: { ...state.detail, ...payload.detail },
      };
    },
  },
};
